package com.liujg.future.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Larry
 * @Date: 2021/3/6 16:00
 * @Description: token生成工具类
 */

public class JwtTokenUtils {

    /**
     * 签名
     */
    private static final String SING = "ivORu9ac@zc*xpJx";

    /**
     * 获取token
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        Calendar calendar = Calendar.getInstance();
        //设置过期时间为7天
        calendar.add(Calendar.DATE, 365);
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        String token = builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     *
     * @return
     */
    public static String getToken() {
        Map<String, String> map = new HashMap<String, String>(4);
        return getToken(map);
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取token里的信息
     * @param token
     * @return
     */
    public static DecodedJWT getMsg(String token){
        try {
            return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
